import os
from flask import Flask
from flask import request
from werkzeug.utils import secure_filename

from flowers import flowers
from signs import signs

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024

UPLOAD_PATH = os.path.abspath(os.path.dirname(__file__)) + '/uploads/'
ALLOWED_EXTENSIONS = {'jpg', 'jpeg'}


@app.route('/', methods=['GET'])
def home():
    return '<h1>Home</h1>'


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def upload_file(name):
    if name not in request.files:
        return {'success': 0, 'err_msg': 'no file part'}

    img = request.files.get(name)

    if img.filename == '':
        return {'success': 0, 'err_msg': 'no selected file'}

    if img and allowed_file(img.filename):
        filename = secure_filename(img.filename)
        img_path = UPLOAD_PATH + name + '/' + filename
        img.save(img_path)
        return {'img_path': img_path}

    return {'success': 0, 'err_msg': 'not allowed file'}


@app.route('/classifier/flowers', methods=['POST'])
def classify_flowers():
    result = upload_file('flowers')
    if 'img_path' in result:
        category = flowers.classify_flowers(result['img_path'])
        return {'success': 1, 'category': category}
    return result


@app.route('/classifier/signs', methods=['POST'])
def classify_signs():
    result = upload_file('signs')
    if 'img_path' in result:
        category = signs.classify_signs(result['img_path'])
        return {'success': 1, 'category': category}
    return result


if __name__ == '__main__':
    app.run()
